<template>
  <div class="app-container">
    <el-main id="main-content">
      <div class="content-wrapper">
        <!-- 搜索和操作区域 -->
        <div class="operation-area">
        <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
          <el-form-item>
              <el-input v-model="queryParams.keyword" placeholder="请输入用户名/手机号" clearable @keyup.enter="handleSearch">
              <template #append>
                  <el-button :icon="Search" @click="handleSearch"></el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
              <el-button type="success" @click="handleAdd">添加用户</el-button>
          </el-form-item>
        </el-form>
        </div>

        <!-- 表格区域 -->
        <el-table 
          v-loading="loading" 
          :data="tableData" 
          border 
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="userId" label="ID" width="80" />
          <el-table-column prop="username" label="用户名" min-width="100" />
          <el-table-column prop="phone" label="手机号" min-width="120" />
          <el-table-column prop="email" label="邮箱" min-width="150" />
          <el-table-column prop="idCard" label="身份证号" min-width="180" />
          <el-table-column prop="sex" label="性别" width="80" />
          <el-table-column prop="role" label="角色" width="100" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
                {{ scope.row.status === 'active' ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" min-width="180">
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column prop="updatedAt" label="更新时间" min-width="180">
            <template #default="scope">
              {{ formatDate(scope.row.updatedAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[1, 2, 5, 10]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

        <!-- 用户表单对话框 -->
        <el-dialog
          :title="dialogTitle"
          v-model="dialogVisible"
          width="500px"
          @close="dialogClose"
        >
          <el-form
            ref="userFormRef"
            :model="userForm"
            :rules="userRules"
            label-width="100px"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="userForm.idCard" placeholder="请输入身份证号" />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="userForm.sex">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="角色" prop="role">
              <el-select v-model="userForm.role" placeholder="请选择角色">
                <el-option label="管理员" value="admin" />
                <el-option label="普通用户" value="user" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="userForm.status">
                <el-radio label="active">启用</el-radio>
                <el-radio label="inactive">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
              <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </el-main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

// 查询参数
const queryParams = reactive({
      pageNum: 1,
      pageSize: 10,
      keyword: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const selectedRows = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('') // 'add' 或 'edit'
const dialogTitle = ref('')
const userFormRef = ref(null)
const userForm = reactive({
  userId: undefined,
  username: '',
  phone: '',
  email: '',
  idCard: '',
  sex: '男',
  role: 'user',
  status: 'active',
  password: '',
  createdAt: '',
  updatedAt: '',
  isDeleted: 0
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 日期格式化
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-');
}

// 获取表格数据
const getTableData = () => {
  loading.value = true
  axios.get('/api/user/page', { 
    params: {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      keyword: queryParams.keyword
    } 
  })
  .then(res => {
    console.log('API响应数据:', res.data)
    if (res.data.code === 200) {
      const records = res.data.data.records || []
      
      tableData.value = records
      total.value = res.data.data.total || 0
    } else {
      ElMessage.error(res.data.message || '获取数据失败')
    }
  })
  .catch(error => {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败：' + error.message)
  })
  .finally(() => {
    loading.value = false
  })
}

// 搜索方法
const handleSearch = () => {
  queryParams.pageNum = 1
  getTableData()
}

// 重置查询
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.pageNum = 1
  getTableData()
}

// 分页方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getTableData()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getTableData()
}

// 多选操作
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 添加用户
const handleAdd = () => {
  dialogType.value = 'add'
  dialogTitle.value = '添加用户'
  dialogVisible.value = true
  userForm.userId = undefined
  userForm.username = ''
  userForm.phone = ''
  userForm.email = ''
  userForm.idCard = ''
  userForm.sex = '男'
  userForm.role = 'user'
  userForm.status = 'active'
  userForm.password = ''
  userForm.isDeleted = 0
}

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑用户'
  dialogVisible.value = true
  Object.assign(userForm, row)
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.delete(`/api/user/delete/${row.userId}`)
      .then(res => {
        if (res.data.code === 200) {
          ElMessage.success('删除成功')
          getTableData()
        } else {
          ElMessage.error(res.data.message || '删除失败')
        }
      })
      .catch(error => {
        console.error('删除失败:', error)
        ElMessage.error('删除失败：' + error.message)
      })
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  
  ElMessageBox.confirm('确认要删除选中的用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedRows.value.map(row => row.userId)
    axios.delete('/api/user/batchDelete', { 
      data: ids 
    })
      .then(res => {
        if (res.data.code === 200) {
          ElMessage.success('批量删除成功')
          getTableData()
        } else {
          ElMessage.error(res.data.message || '批量删除失败')
        }
      })
      .catch(error => {
        console.error('批量删除失败:', error)
        ElMessage.error('批量删除失败：' + error.message)
      })
  })
}

// 更新用户状态
const handleStatusChange = (id, status) => {
  console.log('修改状态:', id, status)
  const newStatus = status === 'active' ? 'inactive' : 'active'
  
  axios.put(`/api/user/status/${id}?status=${newStatus}`)
    .then(res => {
      if (res.data.code === 200) {
        ElMessage.success('状态更新成功')
        getTableData() // 刷新数据
      } else {
        ElMessage.error(res.data.message || '状态更新失败')
        getTableData() // 刷新数据
      }
    })
    .catch(error => {
      console.error('状态更新失败:', error)
      ElMessage.error('状态更新失败：' + error.message)
      getTableData() // 刷新数据
    })
}

// 提交表单
const submitForm = () => {
  if (!userFormRef.value) return
  
  userFormRef.value.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        axios.post('/api/user/add', userForm)
          .then(res => {
            if (res.data.code === 200) {
              ElMessage.success('添加成功')
              dialogVisible.value = false
              getTableData()
            } else {
              ElMessage.error(res.data.message || '添加失败')
            }
          })
          .catch(error => {
            console.error('添加失败:', error)
            ElMessage.error('添加失败：' + error.message)
          })
      } else {
        axios.put('/api/user/update', userForm)
          .then(res => {
            if (res.data.code === 200) {
              ElMessage.success('更新成功')
              dialogVisible.value = false
              getTableData()
            } else {
              ElMessage.error(res.data.message || '更新失败')
            }
          })
          .catch(error => {
            console.error('更新失败:', error)
            ElMessage.error('更新失败：' + error.message)
          })
      }
    }
  })
}

// 对话框关闭
const dialogClose = () => {
  userFormRef.value?.resetFields()
}

// 页面加载时获取数据
onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.operation-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}
</style>